package com.wildwolf.project.wildwolf.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import com.wildwolf.project.wildwolf.model.MagicMessage;
import com.wildwolf.project.wildwolf.providers.AvatarProvider;
import com.wildwolf.project.wildwolf.service.Contact;
import com.wildwolf.project.wildwolf.utils.SortedList;
import com.wildwolf.project.wildwolf.R;

public class MagicMessageAdapter extends BaseAdapter implements Filterable {
	private static final String TAG = MagicMessageAdapter.class.getSimpleName();
	/**
	 * 消息排序
	 */
	private final ComparatorMagicMessageListByTimestampAndDistance<MagicMessage> messageComparator = new ComparatorMagicMessageListByTimestampAndDistance<MagicMessage>();
	private List<MagicMessage> magicMessages;
	/**
	 * 所有的消息
	 */
	private final List<MagicMessage> allMagicMessage = new SortedList<MagicMessage>(new LinkedList<MagicMessage>(), messageComparator);
	/**
	 * 消息过滤
	 */
	private final Filter messageFilter = new MagicMessageFilter();
	
	private final Context context;
	
	private LayoutInflater messageInflater;


	/**
	 * Create a ContactListAdapter.
	 * 
	 * @param c
	 *            the android context
	 */
	public MagicMessageAdapter(final Context context) {
		magicMessages = allMagicMessage;
		this.context = context;
		messageInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return magicMessages.size();
	}

	@Override
	public Object getItem(int position) {
		return magicMessages.get(position);
	}

	@Override
	public long getItemId(int position) {
		return magicMessages.get(position).hashCode();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (convertView == null) {
			v = messageInflater.inflate(R.layout.contactlistcontact, null);
		}
		MagicMessage magicMessage = magicMessages.get(position);
		bindView(v,magicMessage);
		return v;
	}

	/**
	 * Put a contact in the list.
	 * 
	 * @param c
	 *            the contact
	 */
	public void put(Contact c) {
	
	}

	/**
	 * Remove a contact from the list.
	 * 
	 * @param c
	 *            the contact
	 */
	public void remove(Contact c) {
	}

	/**
	 * Clear the contact list.
	 */
	public void clear() {
	}

	@Override
	public Filter getFilter() {
		return  null;
	}

	/**
	 * Bind a contact to the view.
	 * 
	 * @param view
	 *            the row view.
	 * @param curContact
	 *            the contact.
	 */
	private void bindView(View view, MagicMessage magicMessage) {
	/*	if (magicMessage != null) {
			TextView v = (TextView) view.findViewById(R.id.contactlistpseudo);
			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(context);
			if (settings.getBoolean(WildWolfApplication.SHOW_JID, false))
				v.setText(curContact.getJID());
			else
				v.setText(curContact.getName());
			v = (TextView) view.findViewById(R.id.contactlistmsgperso);
			v.setText(curContact.getMsgState());
			ImageView img = (ImageView) view.findViewById(R.id.avatar);
			String avatarId = curContact.getAvatarId();
			int contactStatus = curContact.getStatus();
			Drawable avatar = getAvatarStatusDrawable(avatarId);
			img.setImageDrawable(avatar);
			img.setImageLevel(contactStatus);
		}*/
	}

	/**
	 * Get a LayerDrawable containing the avatar and the status icon. The status
	 * icon will change with the level of the drawable.
	 * 
	 * @param avatarId
	 *            the avatar id to retrieve or null to get default
	 * @return a LayerDrawable
	 */
	private Drawable getAvatarStatusDrawable(String avatarId) {
		Drawable avatarDrawable = null;
		if (avatarId != null) {
			Uri uri = AvatarProvider.CONTENT_URI.buildUpon()
					.appendPath(avatarId).build();
			InputStream in = null;
			try {
				try {
					in = context.getContentResolver().openInputStream(uri);
					avatarDrawable = Drawable.createFromStream(in, avatarId);
				} finally {
					if (in != null)
						in.close();
				}
			} catch (IOException e) {
				Log.w(TAG, "Error while setting the avatar " + avatarId, e);
			}
		}
		if (avatarDrawable == null)
			avatarDrawable = context.getResources().getDrawable(
					R.drawable.wildwolf_launcher_icon_silver);
		LayerDrawable ld = (LayerDrawable) context.getResources().getDrawable(
				R.drawable.avatar_status);
		ld.setLayerInset(1, 36, 36, 0, 0);
		ld.setDrawableByLayerId(R.id.avatar, avatarDrawable);
		return ld;
	}

	/**
	 * Put a contact in a list. Helper method.
	 * 
	 * @param c
	 *            the contact
	 * @param list
	 *            the list
	 */
	private void put(Contact c, List<Contact> list) {
		list.remove(c);
		list.add(c);
	}


	/**
	 * Set the list to display only the online contacts.
	 * 
	 * @param online
	 *            true to display only online contacts
	 */

	/**
	 * A Filter which select Contact to display by searching in ther Jid.
	 */
	private class MagicMessageFilter extends Filter {

		/**
		 * Create a ContactFilter.
		 */
		public MagicMessageFilter() {
		}

		@Override
		protected Filter.FilterResults performFiltering(CharSequence constraint) {
			Log.d(TAG, "performFiltering");
		/*	List<Contact> result = mCurrentList;
			if (constraint.length() > 0) {
				result = new LinkedList<Contact>();
				for (Contact c : mCurrentList) {
					if (c.getJID().contains(constraint))
						result.add(c);
				}
			}
			Filter.FilterResults fr = new Filter.FilterResults();
			fr.values = result;
			fr.count = result.size();
			return fr;*/
			return null;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected void publishResults(CharSequence constraint,
				Filter.FilterResults results) {/*
			Log.d(TAG, "publishResults");
			List<Contact> contacts = (List<Contact>) results.values;
			mCurrentList = contacts;
			notifyDataSetChanged();*/
		}
	}

	/**
	 * 消息排序
	 * 
	 * @author LEON
	 * 
	 * @param <T>
	 */
	private static class ComparatorMagicMessageListByTimestampAndDistance<T>
			implements Comparator<T> {
		/**
		 * Constructor.
		 */
		public ComparatorMagicMessageListByTimestampAndDistance() {
		}

		@Override
		public int compare(T message1, T message2) {
			if (((MagicMessage) message1).getMessageTimestamp().getTime() < ((MagicMessage) message2)
					.getMessageTimestamp().getTime()) {
				return 1;
			} else
				// 此处省略了两者的空间距离算法
				return 1;
		}
	}

}
